﻿using System;
using System.IO;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Graphics.PackedVector;

namespace Game500.Client.Src
{
  public class ResourceManager
  {
    private readonly ContentManager myContentManager;
    private readonly GraphicsDevice myDevice;
    private readonly string myRootDirPath;
    private SpriteFont myFont;

    public ResourceManager(ContentManager contentManager, GraphicsDevice device, string rootDirPath)
    {
      myContentManager = contentManager;
      myDevice = device;
      myRootDirPath = rootDirPath;
      if (!Directory.Exists(rootDirPath)) throw new Exception(string.Format("Target directory '{0}' does not exists", rootDirPath));
      myFont = contentManager.Load<SpriteFont>("BaseFont");
    }

    public Texture2D GetTexture(string fileName)
    {
      string path = Path.Combine(myRootDirPath, fileName);
      var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
      Texture2D texture = Texture2D.FromStream(myDevice, stream);
      PremultiplyAlphas(texture);
      return texture;
    }

    public SpriteFont Font { get { return myFont; } }

    private static void PremultiplyAlphas(Texture2D ret)
    {
      var data = new Byte4[ret.Width * ret.Height];
      ret.GetData(data);
      for (int i = 0; i < data.Length; i++)
      {
        Vector4 vec = data[i].ToVector4();
        float alpha = vec.W / 255.0f;
        var a = (int)(vec.W);
        var r = (int)(alpha * vec.X);
        var g = (int)(alpha * vec.Y);
        var b = (int)(alpha * vec.Z);
        var packed = (uint)(
                             (a << 24) +
                             (b << 16) +
                             (g << 8) +
                             r
                           );

        data[i].PackedValue = packed;
      }
      ret.SetData(data);
    }
  }
}